var editIndex = undefined;
var pageContext;
function showMsgFade(msg) {
  if (!msg) {
    msg = '系统异常';
  }
  $.messager.show({
    title : '提示',
    msg : msg,
    timeout : 3000,
    showType : 'fade'
  });
}

function errorHandler(xhr) {
  if (xhr.status == 555) {
    location.href = 'index.html';
  }
}

/**
 * 编辑单元格通用封装 调用示例$('#xxx').datagrid('selectRow', index).datagrid('editCell',
 * {index:index,field:field});
 */
$.extend($.fn.datagrid.methods, {
  editCell : function(jq, param) {
    return jq.each(function() {
      var opts = $(this).datagrid('options');
      var fields = $(this).datagrid('getColumnFields', true).concat(
          $(this).datagrid('getColumnFields'));
      for (var i = 0; i < fields.length; i++) {
        var col = $(this).datagrid('getColumnOption', fields[i]);
        col.editor1 = col.editor;
        if (fields[i] != param.field) {
          col.editor = null;
        }
      }
      $(this).datagrid('beginEdit', param.index);
      for (var i = 0; i < fields.length; i++) {
        var col = $(this).datagrid('getColumnOption', fields[i]);
        col.editor = col.editor1;
      }
    });
  }
});

/**
 * 结束编辑时调用，传入Id
 */
function endEditing(datagridId) {
  if (editIndex == undefined) {
    return true
  }
  if ($('#' + datagridId).datagrid('validateRow', editIndex)) {
    $('#' + datagridId).datagrid('endEdit', editIndex);
    editIndex = undefined;

    return true;
  } else {
    return false;
  }
}
/**
 * 删除选中行，传入Id
 */
function removeit(datagridId) {
  if (editIndex == undefined) {
    return;
  }
  $('#' + datagridId).datagrid('cancelEdit', editIndex).datagrid('deleteRow',
      editIndex);
  editIndex = undefined;
}
/**
 * 添加一行数据，传入Id
 */
function append(datagridId, object) {
  if (endEditing(datagridId)) {
    $('#' + datagridId).datagrid('appendRow', object);
    editIndex = $('#' + datagridId).datagrid('getRows').length - 1;

    $('#' + datagridId).datagrid('selectRow', editIndex).datagrid('beginEdit',
        editIndex);
  }
}
/**
 * 撤销修改，传入Id
 */
function reject(datagridId) {
  $('#' + datagridId).datagrid('rejectChanges');
  editIndex = undefined;
}

function pageLoad(url, callback) {
  decorate();
  $.get(url, function(data) {
    pageContext = data;
    if (callback)
      callback.call(this, data);
  });
}

function decorate() {
  $(".wide-form input.easyui-textbox").each(function() {
    $(this).textbox({
      "height" : 25
    });
  });
  $(".wide-form input.easyui-combobox").each(function() {
    $(this).textbox({
      "height" : 25
    });
  });
  $(".wide-form a.easyui-linkbutton").each(function() {
    $(this).linkbutton({
      "width" : 100,
      "height" : 30
    });
    $(this).css({
      "background" : "#069cf8"
    });
  });
  $("#toolbar a.easyui-linkbutton").each(function() {
    $(this).linkbutton({
      "width" : 100,
      "height" : 30
    });
  });
  $(".requiredLabel").each(
      function() {
        var content = $(this).html();
        if (content.indexOf("requiredStar") >= 0)
          return;
        var index = content.lastIndexOf("：");
        if (index < 0)
          index = content.length;
        content = content.substring(0, index) + "<b class='requiredStar'>*</b>"
            + content.substring(index);
        $(this).html(content);
      });
}

Date.prototype.format = function(format) {
  var o = {
    "M+" : this.getMonth() + 1, // month
    "d+" : this.getDate(), // day
    "h+" : this.getHours(), // hour
    "m+" : this.getMinutes(), // minute
    "s+" : this.getSeconds(), // second
    "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
    "S" : this.getMilliseconds()
  // millisecond
  }
  if (/(y+)/.test(format))
    format = format.replace(RegExp.$1, (this.getFullYear() + "")
        .substr(4 - RegExp.$1.length));
  for ( var k in o)
    if (new RegExp("(" + k + ")").test(format))
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
          : ("00" + o[k]).substr(("" + o[k]).length));
  return format;
}

function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null)
    return unescape(r[2]);
  return null;
}

function sleep(millisecond) {
  var start = new Date().getTime();
  while (true) {
    if (new Date().getTime() - start > millisecond)
      break;
  }
}

function showMessage(title, msg, timeout, type) {
  $.messager.show({
    title : "<font style='color:white'>" + title + "</font>",
    msg : "<font style='color:red'>" + msg + "</font>",
    timeout : timeout ? timeout : 2000,
    showType : type,
    style : {
      right : '',
      top : document.body.scrollTop + document.documentElement.scrollTop,
      bottom : '',
      background : 'rgb(32,127,212)'
    }
  });
}

function getContextPath() {
  var pathName = document.location.pathname;
  var index = pathName.substr(1).indexOf("/");
  var result = pathName.substr(0, index + 1);
  return result;
}

$.fn.imageResize = function(params) {

  var aspectRatio = 0;
  if (!params.height && !params.width) {
    return this;
  }
  if (params.height && params.width) {
    aspectRatio = params.width / params.height;
  }
  return this
      .one(
          "load",
          function() {
            this.removeAttribute("height");
            this.removeAttribute("width");
            this.style.height = this.style.width = "";

            var imgHeight = this.height, imgWidth = this.width, imgAspectRatio = imgWidth
                / imgHeight, bxHeight = params.height, bxWidth = params.width, bxAspectRatio = aspectRatio;

            if (!bxAspectRatio) {
              if (bxHeight) {
                bxAspectRatio = imgAspectRatio + 1;
              } else {
                bxAspectRatio = imgAspectRatio - 1;
              }
            }

            if ((bxHeight && imgHeight > bxHeight)
                || (bxWidth && imgWidth > bxWidth)) {

              if (imgAspectRatio > bxAspectRatio) {
                bxHeight = ~~(imgHeight / imgWidth * bxWidth);
              } else {
                bxWidth = ~~(imgWidth / imgHeight * bxHeight);
              }

              this.height = bxHeight;
              this.width = bxWidth;
            }
          }).each(function() {

        if (this.complete) {
          $(this).trigger("load");
        }

        this.src = this.src;
      });
};

$.fn.singleupload = function(options) {
  var settings = $.extend({
    action : '#',
    onSuccess : function(remoteFileName) {
    },
    onError : function(message) {
      showMessage("提示", "上传文件失败：" + message, 0, "fade");
    },
    onProgress : function(loaded, total) {
    },
  }, options);

  var fd = new FormData();
  fd.append(settings.inputId, $('#' + settings.inputId).get(0).files[0]);

  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", function(e) {
    var res = JSON.parse(e.target.responseText);
    if (!res.success) {
      settings.onError(res.message);
      return;
    }
    settings.onSuccess(res.remoteFileName);

  }, false);
  xhr.upload.addEventListener("progress", function(e) {
    settings.onProgress(e.loaded, e.total);
  }, false);

  xhr.open("POST", settings.action, true);
  xhr.send(fd);
}
$(document)
    .ajaxError(
        function(event, jqXHR, ajaxSettings, thrownError) {
          var jsonValue = $.parseJSON(jqXHR.responseText);
          $.messager
              .alert(
                  "<font style='color:white'>错误</font>",
                  "<font style='color:red'>" + (jsonValue.exceptionMessage ? jsonValue.exceptionMessage
                      : jsonValue.exceptionClass) + "</font>", 'error');
        });

function loadSuccessHandler(data) {
  enableDataGridEditing($(this), 0);
}

function clickCellHandler(index, field, value) {
  enableDataGridEditing($(this), index, field);
}

function enableDataGridEditing(dg, rowIndex, field) {
  function keydownHandler(event) {
    if (event.keyCode != 13)
      return true;
    if (event.data.nextEditor) {
      focusEditor(event.data.nextEditor);
      return true;
    }
    if (event.data.index + 1 >= dg.datagrid("getRows").length)
      dg.datagrid("appendRow", {});
    dg.datagrid('endEdit', event.data.index);
    dg.datagrid('beginEdit', event.data.index + 1);
    dg.datagrid("highlightRow", event.data.index + 1);
    opts.editIndex = event.data.index + 1;
    var nextEditors = dg.datagrid('getEditors', event.data.index + 1);
    for (var i = 0; i < nextEditors.length; i++) {
      bindEvent(nextEditors[i], nextEditors, event.data.index + 1, i);
      if (i == 0)
        focusEditor(nextEditors[0]);
    }
    return true;
  }
  function bindEvent(editor, editors, row, col) {
    var target = $(editor.target).hasClass('textbox-f') ? $(editor.target)
        .textbox('textbox') : $(editor.target);
    var colOpts = dg.datagrid("getColumnOption", editor.field);
    if (colOpts.editor.keydownHandler != undefined) {
      target.off("keydown", colOpts.editor.keydownHandler).on("keydown",
          colOpts.editor.keydownHandler);
    }
    var nexted = col < editors.length - 1 ? editors[col + 1] : null;
    target.off("keydown", keydownHandler).on("keydown", {
      index : row,
      nextEditor : nexted
    }, keydownHandler);
  }
  function focusEditor(editor) {
    if ($(editor.target).hasClass('textbox-f')) {
      $(editor.target).textbox('textbox').focus();
    } else {
      $(editor.target).focus();
    }
  }
  var opts = dg.datagrid('options');
  if (opts.editIndex != undefined) {
    dg.datagrid("endEdit", opts.editIndex);
  }
  if (rowIndex >= dg.datagrid("getRows").length)
    dg.datagrid("appendRow", {});
  dg.datagrid("beginEdit", rowIndex);
  var editors = dg.datagrid("getEditors", rowIndex);
  for (var j = 0; j < editors.length; j++) {
    var ed = editors[j];
    bindEvent(ed, editors, rowIndex, j);
    if (ed.field === field) {
      focusEditor(ed);
    }
  }
  dg.datagrid("highlightRow", rowIndex);
  opts.editIndex = rowIndex;
}

function HashMap() {
  /** Map大小* */
  var size = 0;
  /** 对象* */
  var entry = new Object();
  /** Map的存put方法* */
  this.put = function(key, value) {
    if (!this.containsKey(key)) {
      size++;
      entry[key] = value;
    }
  }
  /** Map取get方法* */
  this.get = function(key) {
    return this.containsKey(key) ? entry[key] : null;
  }
  /** Map删除remove方法* */
  this.remove = function(key) {
    if (this.containsKey(key) && (delete entry[key])) {
      size--;
    }
  }
  /** 是否包含Key* */
  this.containsKey = function(key) {
    return (key in entry);
  }
  /** 是否包含Value* */
  this.containsValue = function(value) {
    for ( var prop in entry) {
      if (entry[prop] == value) {
        return true;
      }
    }
    return false;
  }
  /** 所有的Value* */
  this.values = function() {
    var values = new Array();
    for ( var prop in entry) {
      values.push(entry[prop]);
    }
    return values;
  }
  /** 所有的 Key* */
  this.keys = function() {
    var keys = new Array();
    for ( var prop in entry) {
      keys.push(prop);
    }
    return keys;
  }
  /** Map size* */
  this.size = function() {
    return size;
  }
  /** 清空Map* */
  this.clear = function() {
    size = 0;
    entry = new Object();
  }
}

Array.prototype.inArray = function(fun) {
  var len = this.length;
  if (typeof fun != "function")
    throw new TypeError();

  var thisp = arguments[1];
  for (var i = 0; i < len; i++) {
    if (i in this && fun.call(thisp, this[i], i, this))
      return i;
  }

  return -1;
};

function hasPermission(moduleName, permissionName) {
  if (pageContext == undefined || pageContext.permissions == undefined)
    return false;
  for (var i = 0; i < pageContext.permissions.length; i++) {
    var permission = pageContext.permissions[i];
    if (permission.uuid == moduleName && permission.code == permissionName) {
      return true;
    }
  }
  return false;
}

function getCurrentUser() {
  if (pageContext == undefined)
    return null;
  return pageContext.currentUser;
}

function getCurrentOrg() {
  if (pageContext == undefined)
    return null;
  return pageContext.currentOrg;
}

function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

$.ajaxSetup({
  cache : false
});

$.extend({
  navigate : function(url) {
    var getTimestamp = new Date().getTime();
    if (url.indexOf("?") > -1) {
      url = url + "&_=" + getTimestamp
    } else {
      url = url + "?_=" + getTimestamp
    }
    window.location.href = url;
  }
});